using System.Collections.Generic;
using System.Linq;
using TeamCityMonitor.Models;
using TeamCityMonitor.Repository;
using TeamCityMonitor.Repository.Caches;
using TeamCitySharp.DomainEntities;

namespace TeamCityMonitor.Manager.CustomCreators
{
    public class HeroCreator : ICustomModelCreator
    {
        private readonly ITeamCityRepository _teamCityRepository;
        private readonly IHeroStoryRepository _storyRepository;
        private readonly IUserPictureRepository _userPictureRepository;

        public HeroCreator(ITeamCityRepository teamCityRepository, IHeroStoryRepository storyRepository, IUserPictureRepository userPictureRepository)
        {
            _teamCityRepository = teamCityRepository;
            _storyRepository = storyRepository;
            _userPictureRepository = userPictureRepository;
        }

        public bool IsActive()
        {
            return Properties.Settings.Default.ShowHeroes;
        }

        public List<CustomModel> GetCustomModels()
        {
            var heroes = _teamCityRepository.GetUsers();

            var heroEntries = new List<CustomModel>();

            heroes.ToList().ForEach(hero => heroEntries.Add(CreateAHero(hero)));

            return heroEntries;
        }

        private CustomModel CreateAHero(User hero)
        {
            var story = GetRandomStory();

            return new CustomModel
                       {
                           Title = story.Title,
                           ImageUrl =  _userPictureRepository.GetUserPicture(hero.Username),
                           ImageCaption = GetUsername(hero),
                           Footer = story.Text
                       };
        }

        private HeroStory GetRandomStory()
        {
            return _storyRepository.GetAStory();
        }

        private string GetUsername(User user)
        {
            if(string.IsNullOrEmpty(user.Name))
            {
                return user.Username;
            }
            return user.Name;
        }
    }
}